﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Security.Cryptography;
using System.Xml;

using X.Common;
using X.Config;
using E.Enum;
using E.Web.Common;
using E.BLL;
using E.Model;

namespace E.Web.UI.Page
{
    public class TeacherBasePage : System.Web.UI.Page
    {
        #region 属性

        private const string LANGUAGE_CONFIGURATION_DIRECTORY = "/LanguageConfiguration/";

        /// <summary>
        /// 配置信息
        /// </summary>
        protected internal GeneralConfigInfo config;

        protected internal int teacherid;
        protected internal string teacherName;
        protected internal EnumTeacherAuthority authority;
        protected internal int areaid;
        protected internal int a2;

        protected internal EnumLanguage language = EnumLanguage.Zh_cn;
        protected internal string languageName;

        /// <summary>
        /// 提示文字
        /// </summary>
        protected internal string msgbox_text = "";

        /// <summary>
        /// 回退链接的内容
        /// </summary>
        protected internal string msgbox_backlink = "javascript:history.back();";

        protected internal string reffer = string.Empty;

        /// <summary>
        /// 当前页面是否被POST请求
        /// </summary>
        protected internal bool ispost;

        protected internal string pagename;
        private string pageFilter = "default,top,management,menu,login,logout,index,forgetpwd";


        protected internal XmlNodeList node;
        protected internal string pageDirectory;

        public IList<string> labels = new List<string>();

        protected bool isGlobal;

        #region 分页相关

        protected internal string mypager = string.Empty;

        protected int count = 0;
        protected int pageIndex = 0;
        protected int currentPgGroup = 0;
        protected int customerPageSize = 0;
        protected int defaultPagesInGroup = 0;

        #endregion

        #endregion

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
        }

        public TeacherBasePage()
        {
            config = GeneralConfigs.GetConfig();

            teacherid = Utils.StrToInt(Utils.GetCookie("teacherid"), -1);
            teacherName = Utils.GetCookie("teachername");
            authority = (EnumTeacherAuthority)Utils.StrToInt(Utils.GetCookie("authority"), -1);
            areaid = Utils.StrToInt(Utils.GetCookie("areaid"), -1);
            a2 = Utils.StrToInt(Utils.GetCookie("a2"), -1);

            //Application["teacherid"] = teacherid;
            //Application["mailday"] = 4;
            //teacherid = 13;
            //teacherName = "internal_1";
            //areaid = 1;
            //authority = EnumTeacherAuthority.Internals;
            //a2 = -1;

            //teacherid = 7;
            //teacherName = "11111111";
            //areaid = 1;
            //authority = EnumTeacherAuthority.Normal;
            //a2 = -1;

            //teacherid = 1;
            //teacherName = "xxx";
            //areaid = 1;
            //authority = EnumTeacherAuthority.Admin;
            //a2 = -1;

            isGlobal = config.IsGlobal;

            pagename = GetPageName(XRequest.GetPageName());
            CheckLogin(pagename);

            #region Global Setting
            if (isGlobal)
            {
                language = (EnumLanguage)Utils.StrToInt(Utils.GetCookie("lan"), 0);
                languageName = language.ToString();
                pagename = GetPageName(XRequest.GetPageName());

                if (pagename.ToLower() != "default" && teacherid == -1)
                {
                    if (pagename.ToLower() != "top")
                    {
                        //ExecuteJS("alert('登录超时，请重新登录'); window.top.location = '/Default.aspx';");
                        //return;
                    }
                }

                pageDirectory = GetPageDirectory();
                node = XMLHelper.GetXMLNodeList(HttpContext.Current.Server.MapPath(LANGUAGE_CONFIGURATION_DIRECTORY + pageDirectory + pagename + ".xml"));
                if (node != null)
                {
                    foreach (XmlNode xn in node)
                    {
                        labels.Add(xn.SelectSingleNode(languageName).FirstChild.Value);
                    }
                }
            }
            #endregion

            ispost = XRequest.IsPost();
            customerPageSize = config.DefaultPageSize;
            defaultPagesInGroup = config.DefaultPagesInGroup;

            ShowPage();
        }
        
        /// <summary>
        /// 页面处理虚方法
        /// </summary>
        protected virtual void ShowPage()
        {
            return;
        }

        protected string GetPageName(string requestPageName)
        {
            int requestPageNameLength = requestPageName.Length;
            return requestPageName.Substring(0, requestPageNameLength - 5);
        }

        protected string GetPageDirectory()
        {
            string serverpath = Server.MapPath("/");
            string currentserverpath = Server.MapPath("");
            string pagepath = "";

            if (currentserverpath.IndexOf(serverpath) != -1)
            {
                pagepath = Server.MapPath("").Replace(serverpath, "") + "\\";
            }
            else
            {
                pagepath = Server.MapPath("").Replace(serverpath.Substring(0, serverpath.Length - 1), "");
            }

            return pagepath;
        }

        protected void Alert(string content)
        {
            ExecuteJS("alert('" + content + "');");
        }

        /// <summary>
        /// 执行javascript
        /// </summary>
        /// <param name="content">JS内容</param>
        protected void ExecuteJS(string content)
        {
            System.Web.HttpContext.Current.Response.Write("<script type=\"text/javascript\">");
            System.Web.HttpContext.Current.Response.Write(content);
            System.Web.HttpContext.Current.Response.Write("</script>");
        }

        protected void InitListItem(int itemCount)
        {
            for (int i = 0; i < itemCount; i++)
            {
                labels.Add("undefined");
            }
        }

        protected string GetTipsByLanguage(EnumAction enumAction)
        {
            string tips = "";

            switch (language)
            { 
                case EnumLanguage.Zh_cn:
                    switch (enumAction) 
                    {
                        case EnumAction.LoginSuccess:
                            tips = "登录成功";
                            break;
                        case EnumAction.LoginFailed:
                            tips = "登录失败";
                            break;
                        default:
                            break;
                    }
                    break;
                case EnumLanguage.En:
                    switch (enumAction)
                    {
                        case EnumAction.LoginSuccess:
                            tips = "Login Success";
                            break;
                        case EnumAction.LoginFailed:
                            tips = "Login Failed";
                            break;
                        default:
                            break;
                    }
                    break;
                case EnumLanguage.De:
                    break;
                case EnumLanguage.Jp:
                    break;
                default:
                    goto case EnumLanguage.Zh_cn;
                    //break;
            }

            return tips;
        }

        protected IList<CourseCategoryModel> GetCourseCategoryList()
        {
            return (new CourseBLL()).GetCourseCategoryList();
        }

        protected IList<DictAreaModel> GetTeacherAreaList(int teacherid)
        { 
            return (new TeacherBLL()).GetTeacherAreaList(teacherid);
        }

        protected Dictionary<int, string> GetCertificateList()
        {
            return (new CourseBLL()).GetCertificateList();
        }

        protected Dictionary<int, string> GetRelationCourseList(int certificateid)
        {
            return (new CourseBLL()).GetRelationCourseList(certificateid);
        }

        /// <summary>
        /// 检查分页值
        /// </summary>
        /// <param name="_pageIndex">当前页</param>
        /// <param name="_currentPgGroup">当前分页组</param>
        /// <param name="_customerPageSize">每页记录数</param>
        protected void CheckPageIndexValue(int _pageIndex, int _currentPgGroup, int _customerPageSize)
        {
            if (_pageIndex > 0)
                pageIndex = _pageIndex;
            if (_currentPgGroup > 0)
                currentPgGroup = _currentPgGroup;
            if (_customerPageSize > 0)
                customerPageSize = _customerPageSize;
        }

        protected void Logout()
        {
            Utils.ClearCookie();
            ExecuteJS("alert('退出成功'); window.top.location= '/Index.aspx';");
        }

        /// <summary>
        /// 获取随机数组
        /// </summary>
        /// <param name="quantity">随机抽取数</param>
        /// <param name="list"></param>
        /// <returns></returns>
        protected IList<int> GetRandomValue(int quantity, IList<int> list)
        {
            IList<int> randomList = new List<int>();
            for (int i = 0; i < quantity; i++)
            {
                Random r = new Random();
                int index = r.Next(0, list.Count);
                randomList.Add(list[index]);
                System.Threading.Thread.Sleep(20);
            }
            return randomList;
        }

        protected string Convert2String(IList<int> parms)
        {
            if (parms != null && parms.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (int parm in parms)
                {
                    sb.Append(parm);
                    sb.Append(",");
                }
                string rst = sb.ToString();
                rst = rst.Substring(0, rst.Length - 1);
                return rst;
            }
            else
                return "";
        }

        protected string Convert2String(Dictionary<int, string> parms)
        {
            if (parms != null && parms.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (KeyValuePair<int, string> kvp in parms)
                {
                    sb.Append(kvp.Key);
                    sb.Append(",");
                }
                string rst = sb.ToString();
                rst = rst.Substring(0, rst.Length - 1);
                return rst;
            }
            else
                return "";
        }

        protected string[] GetArray(string value)
        {
            string[] array;
            if (value.IndexOf(",") != -1)
            {
                array = value.Split(',');
            }
            else
                array = new string[] { value };
            return array;
        }

        private void CheckLogin(string pagename)
        {
            if (teacherid == -1)
            {
                if (pageFilter.IndexOf(pagename) == -1)
                {
                    ExecuteJS("alert('登录超时，请重新登录'); window.top.location = '/Index.aspx';");
                    return;
                }
            }
        }

        protected int GetCourseWarePageCount(int courseid)
        {
            return (new CourseBLL()).GetCourseWarePageCount(courseid);
        }

        protected int GetCurrentPageWithPercent(int percent, int maxpage)
        {
            double p = (double)(percent / 100);
            return Convert.ToInt32(Math.Round(maxpage * p, 0));
        }

    }
}